package com.zcxy360.sandtable.util;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelUtil {
	
	public static List<List<String>> readStream(InputStream inputStream){
		Workbook workbook;
		try {
			workbook = WorkbookFactory.create(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析excel文件失败");
		}
		return readWorkbook(workbook);
	}
	public static List<List<String>> readFile(File excelFile){
		Workbook workbook;
		try {
			workbook = WorkbookFactory.create(excelFile);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析excel文件失败");
		}
		return readWorkbook(workbook);
	}
	private static List<List<String>> readWorkbook(Workbook workbook) {
		Sheet sheet = workbook.getSheetAt(0);
		Iterator<Row> rowIterator = sheet.iterator();
		Row row;
		Cell cell;
		List<List<String>> lists = new ArrayList<>();
		List<String> list ;
		Iterator<Cell> cellIterator;
		boolean firstRow = true;
		while(rowIterator.hasNext()) {
			row = rowIterator.next();
			if(firstRow) {
				firstRow = false;
				continue;
			}
			cellIterator = row.cellIterator();
			list = new ArrayList<>();
			while(cellIterator.hasNext()) {
				cell = cellIterator.next();
				cell.setCellType(CellType.STRING);
				list.add(cell.getStringCellValue());
			}
			lists.add(list);
		}
		return lists;
	}
	
}